#include "HttpServer.hpp"
#include "protocol.hpp"
#include <iostream>
#include <memory>
#include "Util.hpp"

static void Usage(string str)
{
    cout << "Usage: " << str << " local_port" << endl;
}

enum
{
    DIV_ERR = 1,
    MOD_ERR,
    OP_ERR
};

bool fun(const httpRequest &req, httpResponse &resp)
{
    std::cout << "-------------------http start------------" << std::endl;
    std::cout << req.inbuf << std::endl;
    std::cout << "method: " << req.method << std::endl;
    std::cout << "url: " << req.url << std::endl;
    std::cout << "httpVersion: " << req.httpVersion << std::endl;
    std::cout << "path: " << req.path << std::endl;
    std::cout << "--------------------http end------------" << std::endl;

    resp.respLine = "http/1.1 200 OK\r\n";
    resp.respHeader = "Content-type: text/html\r\n";
    resp.respBlank = "\r\n";
    // resp.body = "<html lang=\"en\"><head><meta charset=\"UTF-8\"><title>for test</title><h1>Welcome</h1></head><body><p>若敢来犯</p></body></html>";
    resp.body;
    if (!Util::readFile(req.path, &resp.body))
    {
        Util::readFile(html_404, &resp.body);   //说明路径不存在，设置路径为404
    }

    //整合，最终发送的是outbuf
    resp.outbuf = resp.respLine;    // 响应行
    resp.outbuf += resp.respHeader; // 资源类型
    resp.outbuf += resp.respBlank;  // 空行
    resp.outbuf += resp.body;       // 响应正文
    return true;
}

int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        Usage(argv[0]);
        exit(USAGE_ERR);
    }

    uint16_t port = atoi(argv[1]);
    unique_ptr<Server> svr(new Server(port, fun));
    svr->initServer();
    svr->start();

    return 0;
}
